//
//  MarketDataService.swift
//  Crypto
//
//  Created by DaleGuo on 2023/9/23.
//

import Combine
import Foundation
import SwiftUI

class MarketDataService {
    @Published var marketData: MarketDataModel? = nil

    var marketDataSubscription: AnyCancellable? // 不放入set中，更加明确

    init() {
        getData()
    }

    func getData() {
        guard let url = URL(string: "https://api.coingecko.com/api/v3/global")
        else {
            return
        }

        // 如果不取消订阅，将会一直监听未来可能的数据，但我们知道不会有持续数据，所以要cancel
        // 抽离出网络访问URLSession的通用部分
        marketDataSubscription = NetWorkingManager.download(url: url)
            // 注意json格式是globalData下包含marketData
            .decode(type: GlobalData.self, decoder: JSONDecoder())
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: NetWorkingManager.handleCompletion, receiveValue: { [weak self] returnedGlobalData in
                self?.marketData = returnedGlobalData.data
                self?.marketDataSubscription?.cancel() // cancle sub
            })
    }
}
